/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.common.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.koron.common.dfs.FastDFSClientWrapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

@Component
public class DocConverterUtils {
	private static final Logger logger = LoggerFactory.getLogger(DocConverterUtils.class);

	private static final String[] FILE_TYPE = new String[] {"doc", "docx", "xlsx", "xls", "pptx", "ppt"};
	
	@Value("${openoffice.host}")
    private String host;
	
	@Value("${openoffice.port}")
    private int port;
	
	public File converter(File file){
		if(file == null){
			return null;
		}
		String fileName = FilenameUtils.getBaseName(file.getName());
		String sourceFileExtension = FilenameUtils.getExtension(file.getName());
		if(!Arrays.asList(FILE_TYPE).contains(sourceFileExtension.toLowerCase())) {
			return null;
		}
		File targetFile;
		if("xlsx".equals(sourceFileExtension) || "xls".equals(sourceFileExtension)){
			targetFile = new File(fileName+".html");
		}else{
			targetFile = new File(fileName+".pdf");
		}
		OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
		try {
			connection.connect();
			DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
			converter.convert(file, targetFile);
		} catch (Exception e) {
			logger.error("文件转换失败："+e.getMessage(),e);
			return null;
		}finally {
			if(connection != null) {
				connection.disconnect();
			}
		}
		return targetFile;
	}
	
	public File converter(MultipartFile file){
		if(file == null){
			return null;
		}
		String fileName = FilenameUtils.getBaseName(file.getOriginalFilename());
		String sourceFileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
		if(!Arrays.asList(FILE_TYPE).contains(sourceFileExtension)) {
			return null;
		}
		File sourceFile = new File(file.getOriginalFilename());
		File targetFile;
		if("xlsx".equals(sourceFileExtension) || "xls".equals(sourceFileExtension)){
			targetFile = new File(fileName+".html");
		}else{
			targetFile = new File(fileName+".pdf");
		}
		OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), sourceFile);
			connection.connect();
			DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
			converter.convert(sourceFile, targetFile);
		} catch (Exception e) {
			logger.error("文件转换失败："+e.getMessage(),e);
			return null;
		}finally {
			if(connection != null) {
				connection.disconnect();
			}
			//删除文件
			if(sourceFile.exists()){
				sourceFile.delete();
			}
		}
		return targetFile;
	} 
	
	@Autowired
    private FastDFSClientWrapper clientWrapper;
	
	public String converterUpdate(MultipartFile file) throws Exception {
		File targetFile = converter(file);
		if(targetFile == null){
			return null;
		}
		InputStream is = new FileInputStream(targetFile);
		String pdfPath = clientWrapper.uploadFile(is,targetFile.length(),FilenameUtils.getExtension(targetFile.getName()));
		is.close();
		if(targetFile.exists()){
			targetFile.delete();
		}
		return pdfPath;
	}
	
	public String converterUpdate(File file) throws Exception {
		File targetFile = converter(file);
		if(targetFile == null){
			return null;
		}
		InputStream is = new FileInputStream(targetFile);
		String pdfPath = clientWrapper.uploadFile(is,targetFile.length(),FilenameUtils.getExtension(targetFile.getName()));
		is.close();
		if(targetFile.exists()){
			targetFile.delete();
		}
		return pdfPath;
	}
}
